package com.example.basic.web.webSocket;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * webSocket 工具类
 */
@Component
@ServerEndpoint("/api/v1/webSocket/{uid}")
@Slf4j
public class WebSocketServerUtil {

    private Session session;
    private static CopyOnWriteArraySet<WebSocketServerUtil > webSocketSet = new CopyOnWriteArraySet<>();
    private static ConcurrentHashMap<String,WebSocketServerUtil > webSocketMap  = new ConcurrentHashMap<>();
    private String uid = null;


    @OnOpen
    public void onOpen(Session session, @PathParam("uid") String uid){
        this.session = session;
        this.uid = uid;
        log.info("WEBSOCKET有新链接请求.链接用户id为"+uid);
        if(webSocketMap .containsKey(uid)){
            webSocketMap .remove(uid);
            webSocketMap .put(uid,this);
            log.info(uid+"用户已有链接,先删除,后新增");
        }else{
            webSocketMap .put(uid,this);
            webSocketSet.add(this);
            log.info(uid+"新增链接");
        }
//        log.info("当前websocket链接有"+webSocketSet.toString());
        log.info("【websocket消息】有新的连接，总数：{}",webSocketMap.size());
    }

    @OnClose
    public void onClose(){
        log.info("WEBSOCKET有新断链请求.断链用户id为"+uid);
        if(webSocketMap.containsKey(uid)){
            webSocketMap.remove(uid);
            //从set中删除
            webSocketSet.remove(this);
            log.info(uid+"断开链接");
        }
//        log.info("当前websocket链接有"+webSocketSet.toString());
        log.info("【websocket消息】连接断开，总数：{}",webSocketSet.size());
    }

    @OnMessage
    public void onMessage(String message ,Session session){
//        log.info("【websocket消息】收到客户端用户"+uid+"发来的消息：{}",message);
//        SocketVo socketVo = JSON.parseObject(message, SocketVo.class);
//        manageMsg(socketVo);
//        sendInfo(message, uid);

    }

    public void sendMessage(String message){
        try {
            this.session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    /**
     * 发送自定义消息
     * */
    public static void sendInfo(String message,String uid) {

        log.info("发送消息到用户:"+uid+"，报文:"+message);
        synchronized (webSocketMap) {
            if (webSocketMap.containsKey(uid)) {
                webSocketMap.get(uid).sendMessage(message);
            } else {
                System.out.println("发送时未找到链接");
            }
        }
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        // 错误处理代码
        System.err.println("WebSocket error: " + throwable.getMessage());
        throwable.printStackTrace();
    }

    /**
     * 判断用户状态
     * @param uid
     * @return
     */
    public static Boolean userStatus(String uid){

        if(webSocketMap.containsKey(uid)){
            return true;
        }else {
            return false;
        }
    }

}
